package com.example.gaoyang.handler;

import com.example.gaoyang.enums.ResultEnum;
import com.example.gaoyang.exception.InvalidParameterException;
import com.example.gaoyang.exception.UnauthorizedException;
import com.example.gaoyang.request.Result;
import com.example.gaoyang.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理未授权异常，返回401状态码
     */
    @ExceptionHandler(UnauthorizedException.class)
    public ResponseEntity<Result> handleUnauthorizedException(UnauthorizedException e) {
        log.error("未授权访问: {}", e.getMessage());
        Result result = ResultUtil.fail(ResultEnum.CLIENT_UN_AUTHORIZED.getCode(), e.getMessage());
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
    }

    /**
     * 处理参数错误异常，返回400状态码
     */
    @ExceptionHandler(InvalidParameterException.class)
    public ResponseEntity<Result> handleInvalidParameterException(InvalidParameterException e) {
        log.error("参数错误: {}", e.getMessage());
        Result result = ResultUtil.fail(ResultEnum.PARAM_ERROR.getCode(), e.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
    }
}
